package com.cqie.hospitalescort.controller;

import com.cqie.hospitalescort.DTO.WeiXinSessionInfoDTO;
import com.cqie.hospitalescort.VO.LoginVO;
import com.cqie.hospitalescort.controller.params.LoginParam;
import com.cqie.hospitalescort.controller.params.RegisterParam;
import com.cqie.hospitalescort.model.Result;
import com.cqie.hospitalescort.service.login.LoginService;
import com.cqie.hospitalescort.service.weixin.WeiXinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@RestController
@Api(value = "登录注册", tags = {"登录注册"})
public class LoginController extends BaseController{

    @Autowired
    private LoginService loginService;

    @Autowired
    private WeiXinService weiXinService;

    @PostMapping("/login")
    @ApiOperation(value = "登录", httpMethod = "POST", response = Result.class, produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<LoginVO> login(@RequestBody LoginParam param) {
        WeiXinSessionInfoDTO sessionInfo = null;
        if (Objects.nonNull(param.getCode())) {
            sessionInfo = weiXinService.getSessionInfo(param.getCode());
        }
        return response(loginService.login(param, sessionInfo));
    }


    @PostMapping("/register")
    @ApiOperation(value = "管理员注册", httpMethod = "POST", response = Result.class, produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<Void> register(@RequestBody RegisterParam param) {
        loginService.register(param);
        return response();
    }

    @PostMapping("/outLogin")
    @ApiOperation(value = "登出", httpMethod = "POST", response = Result.class, produces = MediaType.APPLICATION_JSON_VALUE)
    public Result<Void> logout(HttpServletRequest request, HttpServletResponse response) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            new SecurityContextLogoutHandler().logout(request, response,authentication);
        }
        return response();
    }
}
